#include "verifycodewidget.h"

#include "model/data.h"
#include <QPainter>

VerifyCodeWidget::VerifyCodeWidget(QWidget *parent)
    : QWidget{parent}
    , randomGenerator(model::getTime())
{
    verifyCode = generateVerifyCode();
}

QString VerifyCodeWidget::generateVerifyCode()
{
    QString code;
    for (int i = 0; i < 4; ++i)
    {
        int choose = randomGenerator.generate() % 3;
        if (choose == 0)
        {
            // 每次循环生成一个字符
            int init = 'A';
            init += randomGenerator.generate() % 26;
            code += static_cast<QChar>(init);
        }
        else if (choose == 1)
        {
            int init = 'a';
            init += randomGenerator.generate() % 26;
            code += static_cast<QChar>(init);
        }
        else if (choose == 2)
        {
            int init = 0;
            init += randomGenerator.generate() % 10;
            code += QString::number(init);
        }
    }
    return code;
}

void VerifyCodeWidget::refreshVerifyCode()
{
    verifyCode = generateVerifyCode();
    this->update();
}

bool VerifyCodeWidget::checkVerifyCode(const QString &verifyCode)
{
    return this->verifyCode.compare(verifyCode, Qt::CaseInsensitive) == 0;
}



void VerifyCodeWidget::paintEvent(QPaintEvent *event)
{
    (void) event;
    const int width = 100;
    const int height = 40;

    QPainter painter(this);
    QPen pen;
    QFont font("楷体",24,QFont::Bold,true);
    painter.setFont(font);

    // 画点: 添加随机噪点
    for(int i = 0; i < 400; i++)
    {
        pen = QPen(QColor(randomGenerator.generate() % 256, randomGenerator.generate() % 256,
                          randomGenerator.generate() % 256));
        painter.setPen(pen);
        painter.drawPoint(randomGenerator.generate() % width, randomGenerator.generate() % height);
    }

    // 画线: 添加随机干扰线
    for(int i = 0; i < 20; i++)
    {
        pen = QPen(QColor(randomGenerator.generate() % 256, randomGenerator.generate() % 256, randomGenerator.generate() % 256));
        painter.setPen(pen);
        painter.drawLine(randomGenerator.generate() % width, randomGenerator.generate() % height,
                         randomGenerator.generate() % width, randomGenerator.generate() % height);
    }

    // 绘制验证码
    for(int i = 0; i < verifyCode.size(); i++)
    {
        pen = QPen(QColor(randomGenerator.generate() % 255, randomGenerator.generate() % 255,
                          randomGenerator.generate() % 255));
        painter.setPen(pen);
        painter.drawText(18*i, randomGenerator.generate() % 10, 30, 30, Qt::AlignCenter, QString(verifyCode[i]));
    }

}

void VerifyCodeWidget::mousePressEvent(QMouseEvent *event)
{
    (void)event;
    this->refreshVerifyCode();
}
